<script lang="ts" setup>
import { DatatablefieldService } from '@/services/api/dev/datatablefieldField.service'
import { generateTimestampId } from '@/utils/util'
import type { FormInstance } from 'element-plus'
import { computed, ref } from 'vue'
import { useRequest } from 'vue-request'

interface Field {
  _id: string
  id?: number
  fieldName?: string
  name?: string
  fieldType?: string
  fieldLength?: number
  fieldPrecision?: number
  defaultValue?: string
  isPrimary?: 0 | 1
  isAutoIncrement?: 0 | 1
  isUnique?: 0 | 1
  isIndex?: 0 | 1
  allowNull?: 0 | 1
  config?: string
  description?: string
}

const oldTableData = ref<Field[]>([])
const tableData = ref<Field[]>([])

const currentRow = ref()

const formRef = ref<FormInstance>()
// do not use same name with ref

const isFormDataChange = computed(() => {
  return JSON.stringify(oldTableData.value) !== JSON.stringify(tableData.value)
})

const { loading, refresh } = useRequest(DatatablefieldService.list, {
  defaultParams: [{}],
  onSuccess(data) {
    if (data?.length) {
      const arr: Field[] = data.map((item) => ({
        _id: generateTimestampId('id'),
        ...item,
      }))
      oldTableData.value = JSON.parse(JSON.stringify(arr))
      tableData.value = JSON.parse(JSON.stringify(arr))
    }
  },
})

const handleCurrentChange = (val: Field | undefined) => {
  currentRow.value = val
}

const handelAdd = async (formEl: FormInstance | undefined) => {
  console.log(tableData.value)
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('add!')

      tableData.value.push({
        _id: generateTimestampId('id'),
        name: `name_${tableData.value.length}`,
        fieldName: `name_${tableData.value.length}`,
        fieldType: 'CHAR',
        fieldLength: 200,
        fieldPrecision: 0,
        allowNull: 1,
        config: '{}',
        defaultValue: 'null',
      })
      currentRow.value = tableData.value[tableData.value.length - 1]
    } else {
      console.log('error submit!', fields)
    }
  })
}

const handelDel = async () => {

  let index: number = -1
  tableData.value.forEach((element, i: number) => {
    if (element._id === currentRow.value?._id) {
      index = i
    }
  })
  if (index === -1) return
  tableData.value.splice(index, 1);
}

const handelSave = async (formEl: FormInstance | undefined) => {
  console.log(tableData.value)
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      console.log(tableData)
      currentRow.value = undefined
    } else {
      console.log('error submit!', fields)
    }
  })
}

const handelRest = () => {
  ElMessageBox.confirm(
    '确定放弃修改内容?',
    '警告',
    {
      // confirmButtonText: 'OK',
      // cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      refresh()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Canceled',
      })
    })
}

// 上移
function handelMoveUp() {
  let index: number = -1
  tableData.value.forEach((element, i: number) => {
    if (element._id === currentRow.value?._id) {
      index = i
    }
  })
  if (index === -1) return

  if (index === 0) {
    // 第一个元素上移变成最后一个
    const firstItem = tableData.value.shift()
    if (firstItem) {
      tableData.value.push(firstItem)
    }
    return
  }
  tableData.value = [
    ...tableData.value.slice(0, index - 1),
    tableData.value[index],
    tableData.value[index - 1],
    ...tableData.value.slice(index + 1),
  ]
}

// 下移
function handelMoveDown() {
  let index: number = -1
  tableData.value.forEach((element, i: number) => {
    if (element._id === currentRow.value?._id) {
      index = i
    }
  })
  if (index === -1) return
  if (index === tableData.value.length - 1) {
    // 最后一个元素下移变成第一个
    const lastItem = tableData.value.pop()
    if (lastItem) {
      tableData.value.unshift(lastItem)
    }
    return
  }

  tableData.value = [
    ...tableData.value.slice(0, index),
    tableData.value[index + 1],
    tableData.value[index],
    ...tableData.value.slice(index + 2),
  ]
}

//
const handelChange = (value: unknown, name: string, index: number, row: Field) => {
  console.log(value)
  console.log(name)
  console.log(index)
  console.log(row)

  switch (name) {
    case 'isPrimary':
      if (value === 1) {
        tableData.value.forEach((item) => {
          if (row['_id'] !== item['_id']) {
            item['isPrimary'] = 0 // 情况其他字段主键
          }
        })
        row['isUnique'] = 1 // 主键字段必须唯一
        row['allowNull'] = 0 // 主键字段不允许为null
      }
      break;

    default:
      break;
  }
}
</script>

<template>
  <div class="border border-solid border-gray-200">
    <LTable>
      <template #header>
        <div>
          <el-space>
            <el-button-group>
              <el-button type="primary" @click="handelAdd(formRef)">
                <el-icon>
                  <DocumentAdd />
                </el-icon>
                <span>新增</span>
              </el-button>
              <el-button type="danger" :disabled="!currentRow" @click="handelDel()">
                <el-icon>
                  <Delete />
                </el-icon>
                <span>删除</span>
              </el-button>
            </el-button-group>
            <el-button-group>
              <el-button type="primary" :disabled="!currentRow" @click="handelMoveDown()">
                <el-icon>
                  <SortDown />
                </el-icon>
                <span>向下</span>
              </el-button>
              <el-button type="primary" :disabled="!currentRow" @click="handelMoveUp()">
                <el-icon>
                  <SortUp />
                </el-icon>
                <span>向上</span>
              </el-button>
            </el-button-group>

            <el-button-group>
              <el-button type="primary" @click="handelSave(formRef)" :disabled="!isFormDataChange">
                <el-icon>
                  <Finished />
                </el-icon>
                <span>保存</span>
              </el-button>
              <el-button type="warning" @click="handelRest()" :disabled="!isFormDataChange">
                <el-icon>
                  <Finished />
                </el-icon>
                <span>废弃</span>
              </el-button>
            </el-button-group>
          </el-space>
        </div>
      </template>
      <div class="p-2">
        <el-form ref="formRef" :model="tableData" :show-message="false" inline-message>
          <el-table :data="tableData" v-loading="loading" border style="width: 100%" highlight-current-row
            @current-change="handleCurrentChange">
            <el-table-column prop="fieldName" label="字段名称" width="160px">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'fieldName']" required>
                  <el-input v-model="tableData[$index].fieldName"
                    @change="handelChange($event, 'fieldName', $index, row)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="字段别名" width="160px">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'name']" required>
                  <el-input v-model="tableData[$index].name" @change="handelChange($event, 'name', $index, row)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="fieldType" label="数据类型" width="160px">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'fieldType']" required>
                  <el-select v-model="tableData[$index].fieldType"
                    @change="handelChange($event, 'fieldType', $index, row)">
                    <el-option-group label="数值类型">
                      <el-option label="TINYINT" value="TINYINT" />
                      <el-option label="SMALLINT" value="SMALLINT" />
                      <el-option label="MEDIUMINT" value="MEDIUMINT" />
                      <el-option label="INT" value="INT" />
                      <el-option label="BIGINT" value="BIGINT" />
                      <el-option label="FLOAT" value="FLOAT" />
                      <el-option label="DOUBLE" value="DOUBLE" />
                      <el-option label="DECIMAL" value="DECIMAL" />
                    </el-option-group>

                    <el-option-group label="日期时间类型">
                      <el-option label="DATE" value="DATE" />
                      <el-option label="TIME" value="TIME" />
                      <el-option label="YEAR" value="YEAR" />
                      <el-option label="DATETIME" value="DATETIME" />
                      <el-option label="TIMESTAMP" value="TIMESTAMP" />
                    </el-option-group>

                    <el-option-group label="字符串类型">
                      <el-option label="CHAR" value="CHAR" />
                      <el-option label="VARCHAR" value="VARCHAR" />
                      <el-option label="TINYTEXT" value="TINYTEXT" />
                      <el-option label="TEXT" value="TEXT" />
                      <el-option label="MEDIUMTEXT" value="MEDIUMTEXT" />
                      <el-option label="LONGTEXT" value="LONGTEXT" />
                      <el-option label="BINARY" value="BINARY" />
                      <el-option label="VARBINARY" value="VARBINARY" />
                    </el-option-group>

                    <el-option-group label="JSON类型">
                      <el-option label="JSON" value="JSON" />
                    </el-option-group>

                    <el-option-group label="空间类型">
                      <el-option label="GEOMETRY" value="GEOMETRY" />
                      <el-option label="POINT" value="POINT" />
                      <el-option label="LINESTRING" value="LINESTRING" />
                      <el-option label="POLYGON" value="POLYGON" />
                    </el-option-group>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="fieldLength" label="字段长度" width="120px">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'fieldLength']">
                  <el-input-number class="!w-full" v-model="tableData[$index].fieldLength"
                    @change="handelChange($event, 'fieldLength', $index, row)" :min="1" controls-position="right" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="fieldPrecision" label="小数位数" width="120px">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'fieldPrecision']">
                  <el-input-number class="!w-full" v-model="tableData[$index].fieldPrecision"
                    @change="handelChange($event, 'fieldPrecision', $index, row)" :min="0" controls-position="right" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="isPrimary" label="主键" width="80px" align="center">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'isPrimary']">
                  <el-checkbox class="!mx-auto" :true-value="1" :false-value="0" v-model="tableData[$index].isPrimary"
                    @change="handelChange($event, 'isPrimary', $index, row)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="isAutoIncrement" label="自增" width="80px" align="center">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'isAutoIncrement']">
                  <el-checkbox class="!mx-auto" :true-value="1" :false-value="0"
                    v-model="tableData[$index].isAutoIncrement"
                    @change="handelChange($event, 'isAutoIncrement', $index, row)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="isUnique" label="唯一" width="80px" align="center">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'isUnique']">
                  <el-checkbox class="!mx-auto" :true-value="1" :false-value="0" v-model="tableData[$index].isUnique"
                    @change="handelChange($event, 'isUnique', $index, row)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="isIndex" label="索引" width="80px" align="center">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'isIndex']">
                  <el-checkbox class="!mx-auto" :true-value="1" :false-value="0" v-model="tableData[$index].isIndex"
                    @change="handelChange($event, 'isIndex', $index, row)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="allowNull" label="允许Null" width="90px" align="center">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'allowNull']">
                  <el-checkbox class="!mx-auto" :true-value="1" :false-value="0" v-model="tableData[$index].allowNull"
                    @change="handelChange($event, 'allowNull', $index, row)"
                    :disabled="tableData[$index].isPrimary === 1" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="defaultValue" label="默认值" width="160px">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'defaultValue']">
                  <el-input v-model="tableData[$index].defaultValue"
                    @change="handelChange($event, 'defaultValue', $index, row)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="config" label="字段配置" width="160px">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'config']">
                  <el-input v-model="tableData[$index].config" @change="handelChange($event, 'config', $index, row)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="注释" width="160px">
              <template #default="{ $index, row }">
                <el-form-item class="!m-0" :prop="[$index, 'description']">
                  <el-input v-model="tableData[$index].description"
                    @change="handelChange($event, 'description', $index, row)" />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </LTable>
  </div>
</template>
